package com.aijk.commons.lock.impl;

import com.aijk.commons.lock.Lock;

import java.math.BigInteger;
import java.util.concurrent.TimeUnit;

/**
 * <p>  </p>
 * User: chendw
 * Date: 2016/8/30 8:49
 */
public class IDGenerator {
    private static BigInteger id = BigInteger.valueOf(0);

    private final Lock lock;

    private static final BigInteger INCREMENT = BigInteger.valueOf(1);

    public IDGenerator(Lock lock) {
        this.lock = lock;
    }

    public String getAndIncrement() {
        if (lock.tryLock(3, TimeUnit.SECONDS)) {
            try {
                return getAndIncrement0();
            } finally {
                lock.unlock();
            }
        }
        return getAndIncrement0();
    }

    private String getAndIncrement0() {
        String s = id.toString();
        id = id.add(INCREMENT);
        return s;
    }
}
